package com.gjs.intranet.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gjs.common.enums.entity.LibraryAttachFileTypeEnum;
import com.gjs.common.exception.BizException;
import com.gjs.common.manager.FileChunkUtils;
import com.gjs.common.manager.response.RspBody;
import com.gjs.common.pojo.dto.upload.ChunkDTO;
import com.gjs.intranet.pojo.entity.LibraryAttach;
import com.gjs.intranet.pojo.entity.LibraryBook;
import com.gjs.intranet.pojo.entity.LibraryProject;
import com.gjs.intranet.service.ILibraryAttachService;
import com.gjs.intranet.service.ILibraryBookService;
import com.gjs.intranet.service.ILibraryProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
@RequestMapping("/upload")
@Api(tags = "内网上传NAS接口")
@Slf4j
@RequiredArgsConstructor
public class UploadController {

    @Value("${nas.chunk-buffer-path}")
    private String chunkBufferPath;

    @Value("${nas.target-path}")
    private String targetPath;

    private final ILibraryAttachService attachService;

    private final ILibraryProjectService projectService;

    private final ILibraryBookService bookService;

    @PostMapping("/project")
    @ApiOperation("上传项目[原始素材文件/缴送成品/缴送附属品]")
    public RspBody project(Long projectId, LibraryAttachFileTypeEnum fileType, ChunkDTO chunkDTO, HttpServletResponse response) {
        try {
            // 查询项目号
            LibraryProject project = projectService.getById(projectId);
            Assert.notNull(project, "找不到该项目");
            // 查询书号
            LibraryBook book = bookService.getById(project.getBookId());
            Assert.notNull(book, "找不到该图书");
            // 目标文件路径组装
            String[] pathParams = new String[]{
                    targetPath, // 目标目录
                    book.getIsbn(), // 书号
                    project.getErpProjectSn(), // 项目号
                    chunkDTO.getIdentifier(), // 文件唯一标识
                    chunkDTO.getFilename() // 文件名
            };
            String targetFilename = StringUtils.arrayToDelimitedString(pathParams, File.separator);

            FileChunkUtils.upload(targetFilename, chunkBufferPath, chunkDTO);
            if (Files.exists(Paths.get(targetFilename))) {
                LambdaQueryWrapper<LibraryAttach> checkWrapper = new LambdaQueryWrapper<>();
                checkWrapper
                        .eq(LibraryAttach::getProjectId,projectId)
                        .eq(LibraryAttach::getFileType,fileType)
                        .eq(LibraryAttach::getNasPath,targetFilename);

                LibraryAttach attach = new LibraryAttach();
                attach.setProjectId(projectId);
                attach.setFileType(fileType);
                attach.setFilename(chunkDTO.getFilename());
                attach.setFileSize((int) Paths.get(targetFilename).toFile().length());
                attach.setNasPath(targetFilename);
                attachService.saveOrUpdate(attach,checkWrapper);
            }
        } catch (Exception e) {
            // 当发生错误时，返回HTTP 500以便前端组件判定分块是否成功上传
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw new BizException(e.getMessage());
        }

        return RspBody.success();
    }

    @PostMapping("/book")
    @ApiOperation("上传图书[数字资源]")
    public RspBody book(Long bookId, ChunkDTO chunkDTO, HttpServletResponse response) {
        try {
            // 查询书号
            LibraryBook book = bookService.getById(bookId);
            Assert.notNull(book, "找不到该图书");
            // 目标文件路径组装
            String[] pathParams = new String[]{
                    targetPath, // 目标目录
                    book.getIsbn(), // 书号
                    LibraryAttachFileTypeEnum.DIGITAL_RESOURCES.getText(), // 项目号
                    chunkDTO.getIdentifier(), // 文件唯一标识
                    chunkDTO.getFilename() // 文件名
            };
            String targetFilename = StringUtils.arrayToDelimitedString(pathParams, File.separator);

            FileChunkUtils.upload(targetFilename, chunkBufferPath, chunkDTO);
            if (Files.exists(Paths.get(targetFilename))) {
                LambdaQueryWrapper<LibraryAttach> checkWrapper = new LambdaQueryWrapper<>();
                checkWrapper
                        .eq(LibraryAttach::getBookId,bookId)
                        .eq(LibraryAttach::getFileType,LibraryAttachFileTypeEnum.DIGITAL_RESOURCES)
                        .eq(LibraryAttach::getNasPath,targetFilename);

                LibraryAttach attach = new LibraryAttach();
                attach.setBookId(bookId);
                attach.setFileType(LibraryAttachFileTypeEnum.DIGITAL_RESOURCES);
                attach.setFilename(chunkDTO.getFilename());
                attach.setFileSize((int) Paths.get(targetFilename).toFile().length());
                attach.setNasPath(targetFilename);
                attachService.saveOrUpdate(attach,checkWrapper);
            }
        } catch (Exception e) {
            // 当发生错误时，返回HTTP 500以便前端组件判定分块是否成功上传
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw new BizException(e.getMessage());
        }

        return RspBody.success();
    }
}